#import "CityListViewController.h"

@interface CityListViewController ()
@property (nonatomic, retain) UIImageView* checkImgView;
@property NSUInteger curSection;
@property NSUInteger curRow;
@end

@implementation CityListViewController

#define CHECK_TAG 1110

@synthesize cities, keys, checkImgView, curSection, curRow;
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 60.0 ;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.checkImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"check"]];
    checkImgView.tag = CHECK_TAG;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"   
                                                   ofType:@"plist"]; 
    self.cities = [[NSDictionary alloc]   
                        initWithContentsOfFile:path];
    
    self.keys = [[cities allKeys] sortedArrayUsingSelector:  
                    @selector(compare:)];
    ///////////////////////////////////////////////
    
    UIImage *headImg=[UIImage imageNamed:@"navigation@2x"];
    headImg=[Tools resizeImageToSize:headImg toSize:CGSizeMake(320, 44)];
//    UINavigationBar *navBar = self.navigationController.navigationBar;
//#define kSCNavBarImageTag 10
//    if ([navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
//    {
//        [navBar setBackgroundImage:headImg forBarMetrics:UIBarMetricsDefault];
//    }
//    else
//    {
//        UIImageView *imageView = (UIImageView *)[navBar viewWithTag:kSCNavBarImageTag];
//        if (imageView == nil)
//        {
//            imageView = [[UIImageView alloc] initWithImage:
//                         headImg];
//            [imageView setTag:kSCNavBarImageTag];
//            [navBar insertSubview:imageView atIndex:0];
//            //[imageView release];
//        }
//    }
    UIColor* myfont=[UIColor whiteColor];
    UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(90, 0, 140, 40)];
    titleLb.text=@"选择城市";
    titleLb.font=[UIFont systemFontOfSize:22];
    titleLb.textColor=myfont;
    titleLb.textAlignment=UITextAlignmentCenter;
    titleLb.backgroundColor=[UIColor clearColor];
    self.navigationItem.titleView=titleLb;
    
    //返回按钮
    
    CGRect frame_img= CGRectMake(0, 1, 25/2, 41/2);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back1.png"];
    
    CGRect frameBtn= CGRectMake(0, 0,50, 41/2);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    
    [homeBtn addTarget:self action:@selector(back2HomeFn) forControlEvents:UIControlEventTouchUpInside];
    
    [homeBtn addSubview:backView];
    UILabel* backLb=[[UILabel alloc] initWithFrame:CGRectMake(14, 1, 28, 20)];
    backLb.text=@"返回";
    backLb.font=[UIFont boldSystemFontOfSize:14];
    backLb.textColor=[UIColor whiteColor];
    backLb.backgroundColor=[UIColor clearColor];
    [homeBtn addSubview:backLb];
    
    
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
     
}
-(void)back2HomeFn{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.keys = nil;
    self.cities = nil;
    self.checkImgView = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSString *key = [keys objectAtIndex:section];  
    NSArray *citySection = [cities objectForKey:key];
    return [citySection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    NSString *key = [keys objectAtIndex:indexPath.section];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    } else {
        for (UIView *view in cell.contentView.subviews) {
            if (view.tag == CHECK_TAG) {
                if (indexPath.section != curSection || indexPath.row != curRow)
                    checkImgView.hidden = true;
                else
                    checkImgView.hidden = false;
            }
        }
    }
    
    // Configure the cell...
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    cell.textLabel.text = [[cities objectForKey:key] objectAtIndex:indexPath.row];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{  
    NSString *key = [keys objectAtIndex:section];
    key=[key uppercaseString];
    return key;  
}  
 
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView  
{  
    return keys;  
} 

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    //clear previous selection first
    [checkImgView removeFromSuperview];
    
    //add new check mark
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    
    //make sure the image size is fit for cell height;
    
    CGRect cellRect = cell.bounds;
    float imgHeight = cellRect.size.height * 2 / 3; // 2/3 cell height
    float imgWidth = 20.0; //hardcoded
    
    
    checkImgView.frame = CGRectMake(cellRect.origin.x + cellRect.size.width - 100, //shift for index width plus image width 
                                    cellRect.origin.y + cellRect.size.height / 2 - imgHeight / 2, 
                                    imgWidth, 
                                    imgHeight);
    
    [cell.contentView addSubview:checkImgView];
    checkImgView.hidden = false;
    
    curSection = indexPath.section;
    curRow = indexPath.row;
    NSString *key = [keys objectAtIndex:indexPath.section];
    NSArray* list=[cities objectForKey:key];
    int cityId=curSection*100+curRow;
    
    if (cityId==0) {
        cityId=10000;
    }

    
    NSString* city=[list objectAtIndex:curRow];
    NSLog(@"city==%@",city);
    NSLog(@"cityId==%d",cityId);
    //
    NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:city,@"cityName",[NSString stringWithFormat:@"%d",cityId],@"cityId", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCompanyListFn" object:dic];
    [self.navigationController popViewControllerAnimated:NO];
}

@end
